#!/bin/bash
# CAN SDK编译脚本

echo "🔧 编译六维力传感器CAN SDK"
echo "========================="

# 检查编译器
if ! command -v g++ &> /dev/null; then
    echo "❌ 未找到g++编译器"
    exit 1
fi

# 检查系统是否支持CAN
if [ ! -d "/sys/class/net" ]; then
    echo "⚠️  系统可能不支持网络接口，CAN功能可能受限"
fi

# 编译参数
CXX_FLAGS="-std=c++14 -Wall -Wextra -O2 -pthread"
INCLUDES=""
LIBS=""

# 确定脚本所在目录和源文件目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "📁 创建build目录..."
mkdir -p build

echo "🔨 编译SDK库..."
if [ ! -f "six_axis_sensor_can_sdk.cpp" ]; then
    echo "❌ 未找到源文件 six_axis_sensor_can_sdk.cpp"
    echo "💡 请确保在正确的目录中运行此脚本"
    exit 1
fi

g++ ${CXX_FLAGS} ${INCLUDES} -c six_axis_sensor_can_sdk.cpp -o build/six_axis_sensor_can_sdk.o
if [ $? -ne 0 ]; then
    echo "❌ SDK库编译失败"
    exit 1
fi

echo "🔨 编译示例程序..."
if [ ! -f "can_sdk_example.cpp" ]; then
    echo "❌ 未找到源文件 can_sdk_example.cpp"
    exit 1
fi

g++ ${CXX_FLAGS} ${INCLUDES} can_sdk_example.cpp build/six_axis_sensor_can_sdk.o ${LIBS} -o build/can_sdk_example
if [ $? -ne 0 ]; then
    echo "❌ 示例程序编译失败"
    exit 1
fi

echo "📦 创建静态库..."
ar rcs build/libsix_axis_sensor_can.a build/six_axis_sensor_can_sdk.o

echo "✅ 编译完成！"
echo ""
echo "📋 生成的文件："
echo "  - build/libsix_axis_sensor_can.a  (静态库)"
echo "  - build/six_axis_sensor_can_sdk.o (目标文件)"
echo "  - build/can_sdk_example           (示例程序)"
echo ""
echo "🚀 运行示例程序："
echo "  sudo ./build/can_sdk_example [CAN接口名]"
echo ""
echo "💡 CAN接口配置参考："
echo "  sudo modprobe can"
echo "  sudo modprobe can_raw"
echo "  sudo modprobe vcan"
echo "  sudo ip link add dev vcan0 type vcan"
echo "  sudo ip link set up vcan0"
echo ""
echo "  # 真实CAN接口 (CAN-FD模式)："
echo "  sudo ip link set dev can1 up type can bitrate 1000000 dbitrate 1000000 fd on"